package linked_list;

public class DeleteGivenValue {

    public static class Node {
        private int value;
        private Node next;

        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    public static Node removeValue(Node head, int num) {
        // head 来到第一个不需要删的位置
        while (head != null) {
            if (head.value != num) {
                break;
            }
            head = head.next;
        }

        Node pre = head;
        Node cur = head;
        while (cur != null) {
            if (cur.value == num) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    public static void printNode(Node head) {
        while (head != null) {
            System.out.print(head.value + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node node5 = new Node(5, null);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(1, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);
        printNode(node1);
        // Node node11 = removeValue(node1, 1);
        // printNode(node11);
        Node node12 = removeValue(node1, 2);
        printNode(node12);

    }
}
